详情参照
https://mp.weixin.qq.com/s?__biz=Mzk3NTIzODAzNw==&mid=2247483793&idx=1&sn=7e642e9aed0fab151dc54e2a2830fef9&chksm=c59fbc3c1ee53ca80e7f271db68ecc6d396ef626d3dc178c7d9e1165f891064d9fa6f50dbc74&mpshare=1&scene=23&srcid=0517TDDoiIUai2pxJ99T9Krh&sharer_shareinfo=d201215ffaa8edab8990f97be8c392ed&sharer_shareinfo_first=d201215ffaa8edab8990f97be8c392ed#rd


//1. 传递临时变量的问题
#include<iostream>
#include<thread>

void foo(int& x)
{
	x += 1;
}
int main()
{	
	int a = 1;
	//1.创建线程,创建线程时就开始启动了
	std::thread thread1(foo,std::ref(a));//采用这种方式进行引用参数传递
	if(thread1.joinable())//判断该线程能否调用join
	{
		//主线程等待子线程运行完毕再返回
		thread1.join();
	}
	else
	{
		//主线程继续运行，当主线程运行完毕之后，不影响子线程的运行
		thread1.detach();
	}
	std::cout << a << std::endl;
	return 0;
}

//2. 传递指针或引用指向局部变量的问题

#include <iostream>
#include <thread>

void foo(int* ptr) {
    std::cout << *ptr << std::endl;
    delete ptr; // 释放内存
}

int main() {
    int* ptr = new int(1);
    std::thread t(foo, ptr);
    t.join();
    return 0;
}
//或者使用std::shared_ptr，避免手动管理内存

#include <iostream>
#include <thread>
#include <memory>

void foo(std::shared_ptr<int> ptr) {
    std::cout << *ptr << std::endl;
}

int main() {
    auto ptr = std::make_shared<int>(1);
    std::thread t(foo, ptr);
    t.join();
    return 0;
}

//3. 传递指针或引用指向已释放的内存的问题

#include <iostream>
#include <thread>
#include <functional>

void foo(int& x) {
    std::cout << x << std::endl;
}

int main() {
    int x = 1;
    std::thread t(foo, std::ref(x)); // 传递变量的引用
    t.join();
    return 0;
}

//4. 类成员函数作为入口函数，类对象被提前释放

#include <iostream>
#include <thread>
#include <memory>

class MyClass {
public:
    void func() {
        std::cout << "Thread " << std::this_thread::get_id() << " started" << std::endl;
        std::cout << "Thread " << std::this_thread::get_id() << " finished" << std::endl;
    }
};

int main() {
    auto obj = std::make_shared<MyClass>();
    std::thread t(&MyClass::func, obj);
    t.join();
    return 0;
}

//5. 入口函数为类的私有成员函数
#include <iostream>
#include <thread>

class MyClass {
private:
    friend void myThreadFunc(MyClass* obj);
    void privateFunc() {
        std::cout << "Thread " << std::this_thread::get_id() << " privateFunc" << std::endl;
    }
};

void myThreadFunc(MyClass* obj) {
    obj->privateFunc();
}

int main() {
    MyClass obj;
    std::thread thread_1(myThreadFunc, &obj);
    thread_1.join();
    return 0;
}